package com.dong.ui.view;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dong.common.pojo.ResultVO;
import com.dong.common.util.RequestUtils;
import com.dong.common.view.CommonView;
import com.dong.module.foodmenu.pojo.FoodMenu;
import com.dong.module.menulog.pojo.MenuLog;
import com.dong.ui.component.CommonDialog;
import com.dong.ui.component.home.FoodListPanel;
import com.dong.ui.util.ComponentUtils;
import com.dong.ui.util.FontUtils;
import com.dong.ui.util.ImageUtils;
import com.dong.ui.util.MessageUtils;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: 陈瑞东
 * @create: 2021-08-27 15:06
 */
public class AddMenuLogFrame extends CommonDialog implements CommonView {
    /*==================组件==================*/
    private static final int WIDTH = 600;
    private static final int HEIGHT = 600;
    private static final int SHOW_IMAGE_WIDTH = 100;
    private static final int SHOW_IMAGE_HEIGHT = 100;
    private static final int DESCTEXTBOX_WIDTH = 500;
    private static final int DESCTEXTBOX_HEIGHT = 150;

    private JLabel titleLabel;

    private JLabel descJLabel;
    private JPanel descTextBox;
    private JTextArea descJTextArea;
    private JScrollPane descScrollpane;

    private JLabel imageIcon;
    private JButton chooseFileBtn;
    private JFileChooser imageFileChooser;

    private JButton saveBtn;
    /*==================组件==================*/
    /*==================参数==================*/
    private FoodLogFrame parentPanel;

    private String filename;
    private String foodId;
    private String id;
    private MenuLog menuLog;
    /*==================参数==================*/
    /*==================标志==================*/
    boolean requestFlag = true;

    /*==================标志==================*/


    @Override
    public void init(Map<String, Object> params) {
        // 设置标题
        setTitle("添加菜单日志");
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        initParams(params);
        initComponent();
        handleView();

        // 设置大小
        setSize(new Dimension(WIDTH, HEIGHT));
        // 设置不可改变大小
        setResizable(false);
        // 设置居中
        setLocationRelativeTo(null);
        // 在显示前处理，否则会被阻塞（模态框），无法加载事件
        handleAction();
        // 设置可见
        setVisible(true);
    }

    @Override
    public void initComponent() {
        titleLabel = new JLabel("添加菜单日志！");
        titleLabel.setFont(FontUtils.TITLE_FONT);

        descTextBox = new JPanel(new BorderLayout());
        descTextBox.setPreferredSize(new Dimension(DESCTEXTBOX_WIDTH, DESCTEXTBOX_HEIGHT));
        descJLabel = new JLabel("描述");
        descJTextArea = new JTextArea();
        descJTextArea.setLineWrap(true);
        descScrollpane = new JScrollPane(descJTextArea);


        imageIcon = new JLabel("请选择图片...");
        imageIcon.setPreferredSize(new Dimension(SHOW_IMAGE_WIDTH, SHOW_IMAGE_HEIGHT));
        chooseFileBtn = new JButton("选择");

        imageFileChooser = new JFileChooser(".");
        // 设置文件过滤器
        FileNameExtensionFilter imageFilter = new FileNameExtensionFilter("jpg & png", "jpg", "png");
        imageFileChooser.addChoosableFileFilter(imageFilter);
        // 取消全部文件过滤选项
        imageFileChooser.setAcceptAllFileFilterUsed(false);

        saveBtn = new JButton("保    存");

        if (menuLog != null) {
            titleLabel.setText("修改第" + menuLog.getCount() + "次日志！");
            descJTextArea.setText(menuLog.getDescription());
            imageIcon.setText("");
            imageIcon.setIcon(ImageUtils.scaleImage(new ImageIcon(menuLog.getImage()), SHOW_IMAGE_WIDTH, SHOW_IMAGE_HEIGHT));
        }
    }

    public void initParams(Map<String, Object> params) {
        if (params != null) {
            parentPanel = (FoodLogFrame) params.get("parent");
            id = (String) params.get("id");
            foodId = (String) params.get("foodId");
        }
        if (StringUtils.isNotBlank(id)) {
            requestLog();
        }
        initParams();
    }

    /**
     * 请求数据
     */
    private void requestLog() {
        Map<String, Object> requestParams = new HashMap<String, Object>() {{
            put("id", id);
        }};
        requestBegin();
        ResultVO<MenuLog> result = (ResultVO<MenuLog>) RequestUtils.sendRequest("log/getById", requestParams);
        if (result.isSuccess()) {
            menuLog = result.getData();
            filename = menuLog.getImage();
        } else {
            MessageUtils.showMessageDialog(this, result.getMessage(), "失败", JOptionPane.ERROR_MESSAGE);
        }
        requestEnd();
    }

    @Override
    public void initParams() {

    }

    @Override
    public void handleView() {
        // 背景容器
        JPanel bgPabel = new JPanel();

        // 外层水平容器
        Box hBox = Box.createHorizontalBox();

        // 外层垂直容器
        Box vBox = Box.createVerticalBox();

        // 标题水平容器
        Box titleBox = Box.createHorizontalBox();

        titleBox.add(titleLabel);

        // 描述提示容器
        Box descLabelBox = Box.createHorizontalBox();
        descLabelBox.add(descJLabel);

        // 描述文本域容器
        descTextBox.add(descScrollpane);

        // 图片选择水平容器
        Box imageIconBox = Box.createHorizontalBox();
        imageIconBox.add(imageIcon);

        // 图片选择按钮水平容器
        Box imageBtnBox = Box.createHorizontalBox();
        imageBtnBox.add(chooseFileBtn);

        // 保存按钮水平容器
        Box saveBox = Box.createHorizontalBox();
        // 使用边界布局使btn占满该行
        JPanel saveBtnPanel = new JPanel(new BorderLayout());

        saveBox.add(saveBtnPanel);
        saveBtnPanel.add(saveBtn);


        // 添加至外层垂直容器
        vBox.add(Box.createVerticalStrut(30));
        vBox.add(titleBox);
        vBox.add(Box.createVerticalStrut(25));
        vBox.add(imageIconBox);
        vBox.add(Box.createVerticalStrut(25));
        vBox.add(imageBtnBox);
        vBox.add(Box.createVerticalStrut(25));
        vBox.add(descLabelBox);
        vBox.add(descTextBox);
        vBox.add(Box.createVerticalStrut(25));
        vBox.add(saveBtnPanel);
        vBox.add(Box.createVerticalStrut(35));

        // 将垂直容器添加至水平容器
        hBox.add(Box.createHorizontalStrut(40));
        hBox.add(vBox);
        hBox.add(Box.createHorizontalStrut(40));

        // 将水平容器添加至背景容器
        bgPabel.add(hBox);

        // 添加容器至该窗体
        this.add(bgPabel);
    }

    @Override
    public void handleAction() {
        // 点击选择按钮事件
        chooseFileBtnClickEvent();

        // 点击保存按钮事件
        saveBtnClickEvent();
    }

    /**
     * 点击保存按钮事件
     */
    private void saveBtnClickEvent() {
        saveBtn.addActionListener(e -> {
            if (!this.requestFlag) {
                return;
            }
            requestBegin();

            // 获取参数
            String description = descJTextArea.getText();
            String filename = this.filename;
            // 参数验证
            if (!preSave(description, filename)) {
                requestEnd();
                return;
            }
            Map<String, Object> params = new HashMap<String, Object>() {{
                put("id", id);
                put("foodId", foodId);
                put("description", description);
                put("filename", filename);
            }};
            // 发起请求
            ResultVO<Void> resultVO = (ResultVO<Void>) RequestUtils.sendRequest("log/save", params);
            if (resultVO.isSuccess()) {
                // 保存成功
                MessageUtils.showMessageDialog(this, "保存成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
                // 可以考虑刷新主页数据
                if (StringUtils.isBlank(id)) {
                    parentPanel.addCount();
                } else {
                    parentPanel.requestMenuLog(menuLog.getCount());
                }
            } else {
                // 保存失败
                MessageUtils.showMessageDialog(this, resultVO.getMessage(), "失败", JOptionPane.INFORMATION_MESSAGE);
            }

            requestEnd();
        });
    }

    /**
     * 点击选择按钮事件
     */
    private void chooseFileBtnClickEvent() {
        chooseFileBtn.addActionListener(e -> {
            int result = imageFileChooser.showOpenDialog(this);
            if (result == JFileChooser.CANCEL_OPTION) {
                return;
            }
            File file = imageFileChooser.getSelectedFile();
            if (file == null) {
                return;
            }
            // 设置文件参数
            filename = file.getAbsolutePath();

            // 将提示文本清空
            imageIcon.setText("");
            // 设置图片
            imageIcon.setIcon(ImageUtils.scaleImage(new ImageIcon(filename), SHOW_IMAGE_WIDTH, SHOW_IMAGE_HEIGHT));
        });
    }


    /**
     * 请求前的参数验证
     * @param description
     * @param filename
     * @return
     */
    private boolean preSave(String description, String filename) {
        if (StringUtils.isBlank(description)) {
            MessageUtils.showMessageDialog(this, "请填写描述！", "保存失败", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        if (StringUtils.isBlank(filename)) {
            MessageUtils.showMessageDialog(this, "请选择图片！", "保存失败", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        return true;
    }

    /**
     * 请求开始
     */
    private void requestBegin() {
        // 设置鼠标图标为加载图标
        this.setCursor(new Cursor(Cursor.WAIT_CURSOR));
        // 设置不能登录
        this.requestFlag = false;
    }

    /**
     * 请求结束
     */
    private void requestEnd() {
        // 还原鼠标图标
        this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        // 设置可以登录
        this.requestFlag = true;
    }

}
